<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .image-container {
      height: 800px;
      margin-bottom: 20px;
    }
    img {
      display: block;
      width: 100%;
      height: auto;
    }
</style>
<body>
    <div class="image-container">
        <img data-src="https://via.placeholder.com/800x600?text=Image+1" alt="Image 1" class="lazy">
    </div>
    <div class="image-container">
        <img data-src="https://via.placeholder.com/800x600?text=Image+2" alt="Image 2" class="lazy">
    </div>
    <div class="image-container">
        <img data-src="https://via.placeholder.com/800x600?text=Image+3" alt="Image 3" class="lazy">
    </div>
</body>
<script>
    /**
     * orientationchange 是一个 JavaScript 事件，
     * 它在设备的屏幕方向发生变化时触发。这对于响应式设计和移动设备的开发非常重要，
     * 因为它允许开发者在用户从竖屏切换到横屏（或反之）时，调整页面布局或执行特定的操作
    */

    function lazyLoad () {
        const lazyImages = document.querySelectorAll('img.lazy');
        lazyImages.forEach(img => {
            const imgRect = img.getBoundingClientRect() // 它返回一个 DOMRect 对象，提供了元素的大小及其相对于视口(viewport)的位置信息。
            if (imgRect.top <= window.innerHeight && imgRect.bottom >= 0 && getComputedStyle(img).display !== 'none') {
                img.src = img.getAttribute('data-src');
                img.classList.remove('lazy')
            }
        })
        // 如果所有图片都已加载，移除事件监听器
        if (document.querySelectorAll('img.lazy').length === 0) {
            window.removeEventListener('scroll', lazyLoad);
            window.removeEventListener('resize', lazyLoad);
            window.removeEventListener('orientationchange', lazyLoad);
        }
    }

    document.addEventListener('DOMContentLoaded', function () {
        window.addEventListener('scroll', lazyLoad)
        window.addEventListener('resize', lazyLoad)
        window.addEventListener('orientationchange', lazyLoad)
        lazyLoad()
    })
</script>
</html>